import '@wangeditor/editor/dist/css/style.css' // 也可以在 <style> 中 import
import { computed, defineComponent, onBeforeUnmount, ref } from 'vue'
import { Editor, Toolbar, getEditor, removeEditor } from '@wangeditor/editor-for-vue'
import cloneDeep from 'lodash.clonedeep'
import request from '@/request'
import { useRoute, useRouter } from 'vue-router'

export default defineComponent({
  name: 'updateBlog',
  components: { Editor, Toolbar },
  setup() {
    const router = useRouter()
    const route = useRoute()
    const editorId = 'TangEditor-3'
    const bId = route.params.bId // 获取当前博客ID

    const editorConfig = { placeholder: '请输入内容...' }// 编辑器无内容提示
    const customPaste = (editor, event, callback) => {
      editor.insertText('')
      callback(true)
    }// 返回 false ，阻止默认粘贴行为
    // 博客数据内容
    const blogData = ref({
      bId: '',
      bTitle: '',
      bSTitle: '',
      bContent: '',
      bCover: '',
      remark: '',
      status: '',
      bLike: '',
      bWatch: '',
      createTime: '',
      updateTime: '',
      delFlag: '',
      tags: [{
        tName: '1',
        status: '0',
        remark: '1',
        tId: '1',
        createTime: '',
        updateTime: '',
        delFlag: '',
      }],
    })
    const headImgSrc = ref('')
    const blogCover = ref('')// 封面上传路径
    const blogCoverBig = ref('')// 查看大图 图片路径
    const blogCoverBigVisible = ref(false)//查看大图
    const showFrameVisible = ref(true)//添加图片边框
    const showCoverVisible = ref(false)//是否显示阅览图片
    const coverImgList = ref([])//图片集合
    const blogTitle = ref('')// 博客标题
    const blogSubTitle = ref('副标题')// 副标题
    const blogRemark = ref('')// 博客备注
    const isEditorShow = ref(false)//有内容则显示
    const defaultContent = ref([])// 博客内容
    // 注意，深度拷贝 content ，否则会报错
    const getDefaultContent = computed(() => cloneDeep(defaultContent.value))

    //上传图片格式转换成局域网路径
    const fnFileUpload = () => {
      return new Promise((resolve, reject) => {
        const formatDate = new FormData();
        formatDate.append('file', coverImgList.value[0].raw)
        request('/api/file/upload', 'POST', formatDate, 'multipart/form-data').then(
          (res) => {
            blogCover.value = res.data
            resolve(res.data)
          },
        ).catch(
          () => {
            reject('')
          },
        )
      })
    }
    const ChangeCover = (file, fileList) => {
      coverImgList.value = fileList
      blogCover.value = file.url
      fnFileUpload()
      showFrameVisible.value = false
      showCoverVisible.value = true
    }// 更改图片
    const showBigCover = () => {
      blogCoverBig.value = blogCover.value
      blogCoverBigVisible.value = true
    }//查看大图
    const removeCoverImg = () => {
      coverImgList.value = []
      showFrameVisible.value = true
      showCoverVisible.value = false
    } // 删除图片
    const title = ref('')
    const blogStatus = ref()
    const buttonDrafts=()=>{
      showArticle.value = true
      showFrameVisible.value = false
      blogCoverBigVisible.value = false
      title.value = '保存草稿'
      blogStatus.value = 0
    }// 保存草稿
    const buttonArticle = () => {
      showArticle.value = true
      showFrameVisible.value = false
      blogCoverBigVisible.value = false
      title.value = '发表文章'
      blogStatus.value = 1
    }// 发表文章按钮

    //提示框
    const showArticle = ref(false)// 弹窗显示
    const messageCancel = () => {showArticle.value = false}//弹窗按钮

    // 获取当前id的博客内容
    const getBlogData = () => {
      request('/api/blogs/getById', 'get', { bId: bId }).then(
        (res) => {
          isEditorShow.value = true
          blogData.value = res.data
          defaultContent.value = JSON.parse(blogData.value.bContent)
          blogTitle.value = blogData.value.bTitle
          blogCover.value = blogData.value.bCover
          console.log(blogCover.value)
          blogRemark.value = blogData.value.remark
        })
      showCoverVisible.value = true
      showArticle.value = false
      blogCoverBigVisible.value = false
    }

    // 确认
    const headleSaveDrafts = () => {
      if (coverImgList.value.length > 0) {
        fnFileUpload().then(() => {updateBlog(blogCover.value,blogStatus.value)})
      } else if (coverImgList.value.length == 0) {
        updateBlog (null,blogStatus.value)
      }
    }

    // 修改接口
    const updateBlog = (newAvatar,blogStatus)=>{
      const editor = getEditor(editorId)
      const contentStr = JSON.stringify(editor.children)
      const params = {
        bCover: newAvatar,
        bTitle: blogTitle.value,
        bSTitle: blogSubTitle.value,
        bContent: contentStr,
        remark: blogRemark.value,
        status: blogStatus,
        bLike: '',
        bWatch: '',
        createTime: '',
        updateTime: '',
        bId: bId,
        delFlag: '',
        tags: [{
          tName: '1',
          status: '0',
          remark: '1',
          tId: '1',
          createTime: '',
          updateTime: '',
          delFlag: '',
        }],
      }
      request('/api/blogs/update', 'POST', params).then(
        (res) => {
          toBackBlog()
        },
      )
    }
    // 跳转到上一个界面
    const toBackBlog = () => {
      router.go(-1)
    }
    // 及时销毁编辑器
    onBeforeUnmount(() => {
      const editor = getEditor(editorId)
      if (editor == null) return
      // 销毁，并移除 editor
      editor.destroy()
      removeEditor(editorId)
    })
    return {
      headImgSrc,
      editorId,
      editorConfig,
      getDefaultContent,
      showCoverVisible,
      blogCover,
      blogCoverBigVisible,
      blogCoverBig,
      showFrameVisible,
      coverImgList,
      showArticle,
      blogRemark,
      blogTitle,
      isEditorShow,
      defaultContent,
      title,
      mode: 'default',
      customPaste,
      buttonArticle,
      toBackBlog,
      messageCancel,
      showBigCover,
      ChangeCover,
      removeCoverImg,
      getBlogData,
      headleSaveDrafts,
      buttonDrafts
    };
  },
  created() {
    this.headImgSrc = JSON.parse(localStorage.getItem('userInfo')).avatar
    this.getBlogData()
  },
})
